package com.wxtf.platform.main.contraceptives;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.wxtf.platform.interfaces.CommonsCallProvider;
import com.wxtf.platform.plugins.user.UserBean;
import com.wxtf.platform.supers.LogicBase;
import com.wxtf.platform.tools.ConstantInfoHelper;
import com.wxtf.platform.tools.AccessDataBaseUtil;
import com.wxtf.platform.tools.FormatUtil;

/**
 * <li>Title: TmaProvide.java</li>
 * <li>Project: baseplatform</li>
 * <li>Package: com.wxtf.platform.main.contraceptives</li>
 * <li>Description: 药具发放领用登记</li>
 * <li>Copyright: Copyright (c) 2012</li>
 * <li>Company: wxthtf Technologies </li>
 * <li>Created on Aug 21, 2012 10:29:02 AM</li>
 * 
 * @author zhanqiulin
 * @version 1.0.0.0
 * 
 */
public class TmaProvide extends LogicBase implements CommonsCallProvider{
	private static final Log log = LogFactory.getLog(TmaProvide.class);

	public TmaProvide(String jsonArray){
 
	}
	
	@Override
	public Object run() {
		Object msg = "";
		try {
			if("queryPage".equals(this.getMethodName())) {
				msg = this.select(this.getLogicData());
			} else if("save".equals(this.getMethodName())) {
				msg = this.insert(this.getLogicData());
			} else if("update".equals(this.getMethodName())) {
				msg = this.update(this.getLogicData());
			} else if("queryPer".equals(this.getMethodName())) {
				msg = this.selectPer(this.getLogicData());
			} else if ("selectTmaDictionaryById".equals(this.getMethodName())) {// 查询药具名称
				msg = this.selectTmaDictionaryById(this.getLogicData());
			} else if("delete".equals(this.getMethodName())) {
				msg = this.delete(this.getLogicData());
			} else if("copySave".equals(this.getMethodName())) {
				msg = this.copySave(this.getLogicData());
			} else if("selectTmaDictionary".equals(this.getMethodName())) {
				msg = this.selectTmaDictionary(this.getLogicData());
			} else if("copy".equals(this.getMethodName())) {
				msg = this.copyHis(this.getLogicData());
			} else {
				msg = "\"没有【" + this.getMethodName() + "】该方法\"";
			}

			if(msg == null || "[null]".equals(msg)) {
				msg = "\"\"";
			}
			if(msg.toString().startsWith("{") || msg.toString().startsWith("[")){
				return msg;
			}
			msg = ConstantInfoHelper.generateJSONString(msg.toString());
		} catch(Exception e) {
			msg = ConstantInfoHelper.generateErrorJSONString();
			log.error(e, e);
		} finally {
			this.clear();
		}
		return msg.toString();
	}

	String[] fields = {"tmapm_id","tbe_id","org_id","tmapm_code","tmapm_style","tmapm_person","tmapm_time","tmapm_begin_time","tmapm_reason","tmapm_last_medicine","tmapm_is_fail","tmapm_fail_reason","tmapm_memo",
			"reserve1","reserve2","reserve3","reserve4","reserve5","create_by","create_time","last_modify_by","last_modify_time"
	};
	@Override
	public Object select(Object jsonArray) throws Exception {
		UserBean user = (UserBean)this.getRequest().getSession().getAttribute("userBean");
		Object[] params = null;
		StringBuffer querySql = new StringBuffer();
		
		if("0".equals(user.getUserId())){
			sql = "from tma_provide_main t left join tb_employee m on t.tbe_id = m.tbe_id left join tb_family_base n on t.tbe_id = n.tbe_id left join tma_provide_detail v on t.tmapm_id = v.tmapm_id left join tma_dictionary w on v.tmad_id = w.tmad_id where 1 = 1";
		} else {
			sql = "from tma_provide_main t left join tb_employee m on t.tbe_id = m.tbe_id left join tb_family_base n on t.tbe_id = n.tbe_id left join tma_provide_detail v on t.tmapm_id = v.tmapm_id left join tma_dictionary w on v.tmad_id = w.tmad_id where t.org_id = '"+user.getCurOrgId()+"'";
		}
		JSONArray array = JSONArray.fromObject(jsonArray);
		String[] fields2 = {"tmad_kind","tmad_id1","tmapm_id","tbe_id","tbe_idcard","org_id","tmapm_code","tmapm_style","tmapm_person","tmapm_time","tmapm_begin_time","tmapm_reason","tmapm_last_medicine","tmapm_is_fail","tmapm_fail_reason","tbe_name",
				"tbe_work_permit","tbe_address","tbe_sex","tbe_age","tbe_qualification","tbfi_children_num","tbfi_spouse_name","tmapd_id","tmad_name","tmapd_num",
				"reserve1","reserve2","reserve3","reserve4","reserve5","create_by","create_time","last_modify_by","last_modify_time"
		};
		if(array.size() > 0) {
			JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
			String personname_query = jsonObject.getString("personname_query");//领药人姓名
			String age_query = jsonObject.getString("age_query");//年龄
			String tmapm_style_query = jsonObject.getString("tmapm_style_query");//发放形式
			String tmapm_time_start = jsonObject.getString("tmapm_time_start");
			String tmapm_time_end = jsonObject.getString("tmapm_time_end");
			String reserve2_query = jsonObject.getString("reserve2_query");
			StringBuffer buff = new StringBuffer();
			if(StringUtils.isNotBlank(tmapm_style_query)){
				buff.append(" and t.tmapm_style = '").append(tmapm_style_query).append("'");
			}
			if(StringUtils.isNotBlank(age_query)){
				buff.append(" and w.tmad_name like '%").append(age_query).append("%'");
			}
			if(StringUtils.isNotBlank(personname_query)){
				buff.append(" and m.tbe_name like '%").append(personname_query).append("%'");
			}
			if(StringUtils.isNotBlank(tmapm_time_start)){
				buff.append(" and t.tmapm_time >= '").append(tmapm_time_start).append("'");
			}
			if(StringUtils.isNotBlank(tmapm_time_end)){
				buff.append(" and t.tmapm_time <= '").append(tmapm_time_end).append("'");
			}
			if(StringUtils.isNotBlank(reserve2_query)){
				if("1".equals(reserve2_query)){
					buff.append(" and t.reserve2 = '").append(reserve2_query).append("'");
				}else{
					buff.append(" and t.reserve2 <> '1'");
				}
			}
			sql += buff.toString();
		}
		String countSql = "select count(*) " + sql;
		querySql.append("select w.tmad_kind,w.tmad_id,t.tmapm_id,t.tbe_id,m.tbe_idcard,t.org_id,t.tmapm_code,t.tmapm_style,t.tmapm_person,t.tmapm_time,t.tmapm_begin_time,t.tmapm_reason,t.tmapm_last_medicine,t.tmapm_is_fail,t.tmapm_fail_reason,m.tbe_name,m.")
				.append("tbe_work_permit,m.tbe_address,m.tbe_sex,m.tbe_age,m.tbe_qualification,n.tbfi_children_num,n.tbfi_spouse_name,v.tmapd_id,w.tmad_name,v.tmapd_num, ")
				.append("t.reserve1,t.reserve2,t.reserve3,t.reserve4,t.reserve5,t.create_by,t.create_time,t.last_modify_by,t.last_modify_time ").append(sql)
				.append(" order by tmapm_time desc, last_modify_time desc");
		return AccessDataBaseUtil.query4SQLPagging(fields2, countSql, querySql.toString(), this.getPage(), this.getPagesize(), params);
	}

	@Override
	public Object insert(Object jsonArray) throws Exception {
		UserBean user = (UserBean)this.getRequest().getSession().getAttribute("userBean");
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		String tmapmid = "";
		String userid = user.getUserId();
		String orgid = user.getCurOrgId();
		StringBuffer buff = new StringBuffer();
		String curTime = FormatUtil.getCurentDateTime();
		String sn = FormatUtil.getCurentDateTime4ms();
		List<String> list = new ArrayList<String>();
		//药具发放主表
		
		int months = jsonObject.containsKey("months") ? Integer.parseInt(jsonObject.getString("months")) : 1;
		Calendar cal = Calendar.getInstance();
		String tmapdate;
		Date d = FormatUtil.getDate(jsonObject.getString("tmapm_time"));
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
		cal.setTime(d);
		buff.setLength(0);
		String reserve2 = jsonObject.getString("reserve2"); 
		List<Object[]> l = new ArrayList<Object[]>();
		if(d != null){
			Calendar maxcal = Calendar.getInstance();
			maxcal.setTime(d);
			maxcal.add(Calendar.MONTH, months);
			buff.append("select tmapm_time,tmapm_id from tma_provide_main where tmapm_time > '").append(format.format(d))
			.append("' and tmapm_time < '").append(format.format(maxcal.getTime()))
			.append("' and tbe_id = '").append(jsonObject.getString("tbe_id")).append("' and org_id = '").append(user.getCurOrgId()).append("' order by tmapm_time");
			l = AccessDataBaseUtil.query(buff.toString(), null);
		}
		if(l.size() > 0){
			return "{\"result\":false,\"resultmessage\":\"调用失败\",\"resultrecord\":\"此员工在所填发放日期当月已经领药，不能再次发放。\"}";
		}
		String tempid = AccessDataBaseUtil.getPKUUID();
		for(int i = 0; i < months; i++){
			buff.setLength(0);
			cal.setTime(d);
			cal.add(Calendar.MONTH, i);
			tmapmid = AccessDataBaseUtil.getPKUUID();
			tmapdate = FormatUtil.safeFormatDate(cal.getTime());
			buff.append("insert into tma_provide_main(tmapm_id,tbe_id,org_id,tmapm_code,tmapm_style,tmapm_person,tmapm_time,tmapm_begin_time,tmapm_reason,")
			.append("tmapm_last_medicine,tmapm_is_fail,tmapm_fail_reason,tmapm_memo,reserve1,reserve2,reserve3,reserve4,reserve5,create_by,create_time,")
			.append("last_modify_by,last_modify_time) values('").append(tmapmid).append("'")
			.append(",'").append(jsonObject.getString("tbe_id")).append("'")
			.append(",'").append(orgid).append("'")
			.append(",'").append("FL"+sn+i).append("'")
			.append(",'").append(jsonObject.getString("tmapm_style")).append("'")
			.append(",'").append(jsonObject.getString("tmapm_person")).append("'")
			.append(",'").append(tmapdate).append("'")
			.append(",'").append(jsonObject.getString("tmapm_begin_time")).append("'")
			.append(",'").append(jsonObject.getString("tmapm_reason")).append("'")
			.append(",'").append(jsonObject.getString("tmapm_last_medicine")).append("'")
			.append(",'").append(jsonObject.getString("tmapm_is_fail")).append("'")
			.append(",'").append(jsonObject.getString("tmapm_fail_reason")).append("'")
			.append(",'").append(jsonObject.getString("tmapm_memo")).append("'")
			.append(",'").append(jsonObject.getString("reserve1")).append("'")
			.append(",'").append(reserve2).append("'")
			.append(",'").append(jsonObject.getString("reserve3")).append("'")
			.append(",'").append(jsonObject.getString("reserve4")).append("'")
			.append(",'").append(tempid).append("'")
			.append(",'").append(userid).append("'")
			.append(",'").append(curTime).append("'")
			.append(",'").append(userid).append("'")
			.append(",'").append(curTime).append("')");
			list.add(buff.toString());
			
			buff.setLength(0);
			//发放子表
			String tmapdid = AccessDataBaseUtil.getPKUUID();
			buff.append("insert into tma_provide_detail(tmapm_id,tmapd_id,tmad_id,tmapd_num,reserve1,reserve2,reserve3,reserve4,reserve5,create_by,create_time,last_modify_by,last_modify_time) values(")
				.append("'").append(tmapmid).append("'")
				.append(",'").append(tmapdid).append("'")
				.append(",'").append(jsonObject.getString("tmad_id")).append("'")
				.append(",'").append(jsonObject.getString("tmapd_num")).append("'")
				.append(",'','','','',''")
				.append(",'").append(userid).append("'")
				.append(",'").append(curTime).append("'")
				.append(",'").append(userid).append("'")
				.append(",'").append(curTime).append("')");
			list.add(buff.toString());
		}
		buff.setLength(0);
		if("1".equals(reserve2)){
			//出库主表
			buff.append("insert into tma_outcome_main(tmaom_id,org_id,tmaom_type,tmaom_is_valid,tmaom_code,tmaom_time,create_by,create_time,last_modify_by,last_modify_time) values(")
				.append("'").append(tmapmid).append("'")
				.append(",'").append(orgid).append("'")
				.append(",'").append("0").append("'")
				.append(",'").append("1").append("'")
				.append(",'").append("KM"+sn).append("'")
				.append(",'").append(curTime).append("'")
				.append(",'").append(userid).append("'")
				.append(",'").append(curTime).append("'")
				.append(",'").append(userid).append("'")
				.append(",'").append(curTime).append("')");
			list.add(buff.toString());
			buff.setLength(0);
			//出库子表
			buff.append("insert into tma_outcome_detail(tmaom_id,tmaod_id,tmad_id,tmaod_num,create_by,create_time,last_modify_by,last_modify_time) values(")
				.append("'").append(tmapmid).append("'")
				.append(",'").append(AccessDataBaseUtil.getPKUUID()).append("'")
				.append(",'").append(jsonObject.getString("tmad_id")).append("'")
				.append(",'").append(Integer.parseInt(jsonObject.getString("tmapd_num"))*months).append("'")
				.append(",'").append(userid).append("'")
				.append(",'").append(curTime).append("'")
				.append(",'").append(userid).append("'")
				.append(",'").append(curTime).append("')");
			list.add(buff.toString());
			buff.setLength(0);
			sql = "select max(a.tmad_begin_time),a.tbe_id,a.tmamvm_cmedicine_des from tma_medicine_vistor_main a where a.tbe_id='"+jsonObject.getString("tbe_id")+"' having max(a.tmad_begin_time) is not null";
			List<Object[]> obs = new ArrayList<Object[]>();
			obs = AccessDataBaseUtil.query(sql, null);
			boolean bool = false;
			if(obs.size() > 0){
				Object[] oarr = obs.get(0);
				if(FormatUtil.getDate(oarr[0].toString()).before(FormatUtil.getDate(jsonObject.getString("tmapm_begin_time"))) 
						&& !oarr[2].toString().equals(jsonObject.getString("tmad_id")) && FormatUtil.getDate(oarr[0].toString()).before(new Date())){
					bool = true;
				}
			}else{
				bool = true;
			}
			//随访登记
			if(bool){
				String tbe_id = jsonObject.getString("tbe_id");
				String tmamvm_id = AccessDataBaseUtil.getPKUUID();
				String tmad_id = jsonObject.getString("tmad_id");
				String tmapm_begin_time = jsonObject.getString("tmapm_begin_time");
				String tmapm_fail_reason = jsonObject.getString("tmapm_fail_reason");
				SimpleDateFormat format2=new SimpleDateFormat("yyyy-MM-dd");
				sql = "select sc_value from t_system_config where sc_key='overdueReminders'";
				List<Object> sc_key = AccessDataBaseUtil.query4List(sql, null);
				int key = sc_key.size() > 0 ? Integer.valueOf(sc_key.get(0).toString()) : 0;
				int num = getMonthNum(format2.parse(tmapm_begin_time), format2.parse(curTime),key);
				buff.append("select count(*) from tma_medicine_vistor_main where tbe_id='").append(tbe_id).append("'");
				int count = AccessDataBaseUtil.queryForInt(buff.toString(), null);
				buff.setLength(0);
				List<Object[]> tempList = null;
				if(count > 0){
					buff.append("select * from (select tmamvm_id,tbe_id,tmamvm_cmedicine_des from tma_medicine_vistor_main where tbe_id='").append(tbe_id).append("' order by last_modify_time desc) a group by a.tbe_id");
					tempList = AccessDataBaseUtil.query(buff.toString(), null);
					buff.setLength(0);
				}
				if(count == 0){
					buff.append("insert into tma_medicine_vistor_main(tmamvm_id,org_id,tbe_id,tmamvm_date,tmamvm_lmedicine_des,tmamvm_lmedicine_time,tmad_id,tmamvm_change_reason,tmamvm_cmedicine_des,tmad_begin_time,tmamvm_memo,reserve5,create_by,create_time,last_modify_by,last_modify_time) values(")
					.append("'").append(tmamvm_id).append("'")
					.append(",'").append(orgid).append("'")
					.append(",'").append(tbe_id).append("'")
					.append(",'").append(curTime).append("'")
					.append(",''")
					.append(",").append(num)
					.append(",''")
					.append(",''")
					.append(",'").append(tmad_id).append("'")
					.append(",'").append(tmapm_begin_time).append("'")
					.append(",''")
					.append(",'").append(tempid).append("'")
					.append(",'").append(userid).append("'")
					.append(",'").append(curTime).append("'")
					.append(",'").append(userid).append("'")
					.append(",'").append(curTime).append("')");
					list.add(buff.toString());
					buff.setLength(0);
				}else{
					buff.append("insert into tma_medicine_vistor_main(tmamvm_id,org_id,tbe_id,tmamvm_date,tmamvm_lmedicine_des,tmamvm_lmedicine_time,tmad_id,tmamvm_change_reason,tmamvm_cmedicine_des,tmad_begin_time,tmamvm_memo,reserve5,create_by,create_time,last_modify_by,last_modify_time) values(")
					.append("'").append(tmamvm_id).append("'")
					.append(",'").append(orgid).append("'")
					.append(",'").append(tbe_id).append("'")
					.append(",'").append(curTime).append("'")
					.append(",'").append(tempList.get(0)[2]).append("'")
					.append(",").append(num)
					.append(",''")
					.append(",'").append(tmapm_fail_reason).append("'")
					.append(",'").append(tmad_id).append("'")
					.append(",'").append(tmapm_begin_time).append("'")
					.append(",''")
					.append(",'").append(tempid).append("'")
					.append(",'").append(userid).append("'")
					.append(",'").append(curTime).append("'")
					.append(",'").append(userid).append("'")
					.append(",'").append(curTime).append("')");
					list.add(buff.toString());
					buff.setLength(0);
				}	
			}
			
		}
			
		String kind = jsonObject.getString("tmad_kind");
		buff.setLength(0);
		buff.append("select TBE_BIRTH_CONTROL_MEASURES from tb_employee where tbe_id='").append(jsonObject.getString("tbe_id")).append("'");
		List<Object> tbebcm = new ArrayList<Object>();
		tbebcm = AccessDataBaseUtil.query4List(buff.toString(), null);
		if(tbebcm != null && tbebcm.size() > 0){
			String str = tbebcm.get(0).toString();
			if(!"104-1".equals(str) && !"104-2".equals(str) && !"104-3".equals(str)){
				if(StringUtils.isNotBlank(kind)){
					buff.setLength(0);
					String s = "";
					if("105-8".equals(kind) || "105-9".equals(kind)){
						s = "104-6";
					}else if("105-7".equals(kind) || "105-2".equals(kind)){
						s = "104-4";
					}else if("105-6".equals(kind)){
						s = "104-5";
					}
					if(!"".equals(s)){
						buff.append("update tb_employee set TBE_BIRTH_CONTROL_MEASURES = '").append(s).append("' where tbe_id = '").append(jsonObject.getString("tbe_id")).append("'");
						list.add(buff.toString());
						buff.setLength(0);
					}
				}
			}
		}
		AccessDataBaseUtil.executeSQLUpdate(list);
		return "\"保存成功\"";
	}
	/**
	 * 共使用多少月
	 * @param date1开始时间
	 * @param date2当前时间
	 * @return
	 */
	public int getMonthNum(Date date1,Date date2,int day) {
		Calendar cal1=Calendar.getInstance();
		cal1.setTime(date1);
		Calendar cal2=Calendar.getInstance();
		cal2.setTime(date2);
		int m1=cal1.get(2),m2=cal2.get(2);
		if (cal2.get(5)<day){
			m2=cal2.get(2)-1;
		}
		if (cal1.get(5)<day){
			m1=cal1.get(2)-1;
		}
		int yue = (cal2.get(1)-cal1.get(1))*12+(m2-m1);		
		return yue;
	}

	@Override
	public Object update(Object jsonArray) throws Exception {
		UserBean user = (UserBean)this.getRequest().getSession().getAttribute("userBean");
		String curTime = FormatUtil.getCurentDateTime();
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		String id = jsonObject.getString("tmapm_id");
		String tmapdid = jsonObject.getString("tmapd_id");
		StringBuffer buff = new StringBuffer();
		String num = jsonObject.getString("tmapd_num");
		String tmadid = jsonObject.getString("tmad_id");
		String reserve2 = jsonObject.getString("reserve2");
		String tempid = jsonObject.getString("reserve5");
		Calendar cal = Calendar.getInstance();
		Date d = FormatUtil.getDate(jsonObject.getString("tmapm_time"));
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
		cal.setTime(d);
		buff.setLength(0);
		List<Object[]> l = new ArrayList<Object[]>();
		if(d != null){
			buff.append("select tmapm_time,tmapm_id from tma_provide_main where tmapm_time like '%").append(format.format(d))
			.append("%' and tbe_id = '").append(jsonObject.getString("tbe_id")).append("' and org_id = '").append(user.getCurOrgId()).append("' order by tmapm_time");
			l = AccessDataBaseUtil.query(buff.toString(), null);
		}
		if(l.size() > 0 && !jsonObject.getString("tmapm_id").equals(l.get(0)[1])){
			return "\"该员工在此发放日期当月或者逐月期间已经领用药具，不能再次发放，可以修改当月的发放记录。\"";
		}
		List<String> sqllist = new ArrayList<String>();
		buff.setLength(0);
		buff.append("update tma_provide_main set ");
		for(int j = 0; j < fields.length-2; j++) {
			buff.append(fields[j]).append(" = '").append(jsonObject.getString(fields[j])).append("',");
		}
		buff.append("last_modify_by = '").append(user.getUserId()).append("',").append("last_modify_time = '").append(curTime).append("'")
		.append(" where tmapm_id = '").append(id).append("'");
		sqllist.add(buff.toString());
		buff.setLength(0);
		buff.append("update tma_provide_detail set tmad_id = '").append(tmadid).append("',tmapd_num = '").append(num).append("' where tmapd_id = '").append(tmapdid).append("'");
		sqllist.add(buff.toString());
		if("1".equals(reserve2)){
			//出库主表
			String tmaom_id = AccessDataBaseUtil.getPKUUID();
			buff.setLength(0);
			buff.append("insert into tma_outcome_main(tmaom_id,org_id,tmaom_type,tmaom_is_valid,tmaom_code,tmaom_time,create_by,create_time,last_modify_by,last_modify_time) values(")
				.append("'").append(tmaom_id).append("'")
				.append(",'").append(user.getCurOrgId()).append("'")
				.append(",'").append("0").append("'")
				.append(",'").append("1").append("'")
				.append(",'").append("KM"+FormatUtil.getCurentDateTime4ms()).append("'")
				.append(",'").append(curTime).append("'")
				.append(",'").append(user.getUserId()).append("'")
				.append(",'").append(curTime).append("'")
				.append(",'").append(user.getUserId()).append("'")
				.append(",'").append(curTime).append("')");
			sqllist.add(buff.toString());
			buff.setLength(0);
			//出库子表
			buff.append("insert into tma_outcome_detail(tmaom_id,tmaod_id,tmad_id,tmaod_num,create_by,create_time,last_modify_by,last_modify_time) values(")
				.append("'").append(tmaom_id).append("'")
				.append(",'").append(AccessDataBaseUtil.getPKUUID()).append("'")
				.append(",'").append(tmadid).append("'")
				.append(",'").append(Integer.parseInt(num)).append("'")
				.append(",'").append(user.getUserId()).append("'")
				.append(",'").append(curTime).append("'")
				.append(",'").append(user.getUserId()).append("'")
				.append(",'").append(curTime).append("')");
			sqllist.add(buff.toString());
			buff.setLength(0);
			buff.setLength(0);
			sql = "select max(a.tmad_begin_time),a.tbe_id,a.tmamvm_cmedicine_des from tma_medicine_vistor_main a where a.tbe_id='"+jsonObject.getString("tbe_id")+"' having max(a.tmad_begin_time) is not null";
			List<Object[]> obs = new ArrayList<Object[]>();
			obs = AccessDataBaseUtil.query(sql, null);
			boolean bool = false;
			if(obs.size() > 0){
				Object[] oarr = obs.get(0);
				if(FormatUtil.getDate(oarr[0].toString()).before(FormatUtil.getDate(jsonObject.getString("tmapm_begin_time"))) 
						&& !oarr[2].toString().equals(jsonObject.getString("tmad_id")) && FormatUtil.getDate(oarr[0].toString()).before(new Date())){
					bool = true;
				}
			}else{
				bool = true;
			}if(bool){
				//随访登记
				String tbe_id = jsonObject.getString("tbe_id");
				String tmamvm_id = AccessDataBaseUtil.getPKUUID();
				String tmad_id = jsonObject.getString("tmad_id");
				String tmapm_begin_time = jsonObject.getString("tmapm_begin_time");
				String tmapm_fail_reason = jsonObject.getString("tmapm_fail_reason");
				String now = FormatUtil.getCurentDate();
				SimpleDateFormat format2=new SimpleDateFormat("yyyy-MM-dd");
				sql = "select sc_value from t_system_config where sc_key='overdueReminders'";
				List<Object> sc_key = AccessDataBaseUtil.query4List(sql, null);
				int key = sc_key.size() > 0 ? Integer.valueOf(sc_key.get(0).toString()) : 0;
				int snum = getMonthNum(format2.parse(tmapm_begin_time), format2.parse(now),key);
				buff.append("select count(*) from tma_medicine_vistor_main where tbe_id='").append(tbe_id).append("'");
				int count = AccessDataBaseUtil.queryForInt(buff.toString(), null);
				buff.setLength(0);
				List<Object[]> tempList = null;
				if(count > 0){
					buff.append("select * from (select tmamvm_id,tbe_id,tmamvm_cmedicine_des from tma_medicine_vistor_main where tbe_id='").append(tbe_id).append("' order by last_modify_time desc) a group by a.tbe_id");
					tempList = AccessDataBaseUtil.query(buff.toString(), null);
					buff.setLength(0);
				}
				if(count == 0){
					buff.append("insert into tma_medicine_vistor_main(tmamvm_id,org_id,tbe_id,tmamvm_date,tmamvm_lmedicine_des,tmamvm_lmedicine_time,tmad_id,tmamvm_change_reason,tmamvm_cmedicine_des,tmad_begin_time,tmamvm_memo,reserve5,create_by,create_time,last_modify_by,last_modify_time) values(")
					.append("'").append(tmamvm_id).append("'")
					.append(",'").append(user.getCurOrgId()).append("'")
					.append(",'").append(tbe_id).append("'")
					.append(",'").append(curTime).append("'")
					.append(",''")
					.append(",").append(snum)
					.append(",''")
					.append(",''")
					.append(",'").append(tmad_id).append("'")
					.append(",'").append(tmapm_begin_time).append("'")
					.append(",''")
					.append(",'").append(tempid).append("'")
					.append(",'").append(user.getUserId()).append("'")
					.append(",'").append(curTime).append("'")
					.append(",'").append(user.getUserId()).append("'")
					.append(",'").append(curTime).append("')");
					sqllist.add(buff.toString());
					buff.setLength(0);
				}else{
					buff.append("insert into tma_medicine_vistor_main(tmamvm_id,org_id,tbe_id,tmamvm_date,tmamvm_lmedicine_des,tmamvm_lmedicine_time,tmad_id,tmamvm_change_reason,tmamvm_cmedicine_des,tmad_begin_time,tmamvm_memo,reserve5,create_by,create_time,last_modify_by,last_modify_time) values(")
					.append("'").append(tmamvm_id).append("'")
					.append(",'").append(user.getCurOrgId()).append("'")
					.append(",'").append(tbe_id).append("'")
					.append(",'").append(curTime).append("'")
					.append(",'").append(tempList.get(0)[2]).append("'")
					.append(",").append(snum)
					.append(",''")
					.append(",'").append(tmapm_fail_reason).append("'")
					.append(",'").append(tmad_id).append("'")
					.append(",'").append(tmapm_begin_time).append("'")
					.append(",''")
					.append(",'").append(tempid).append("'")
					.append(",'").append(user.getUserId()).append("'")
					.append(",'").append(curTime).append("'")
					.append(",'").append(user.getUserId()).append("'")
					.append(",'").append(curTime).append("')");
					sqllist.add(buff.toString());
					buff.setLength(0);
				}
			}
			
		}
		String kind = jsonObject.getString("tmad_kind");
		buff.setLength(0);
		buff.append("select TBE_BIRTH_CONTROL_MEASURES from tb_employee where tbe_id='").append(jsonObject.getString("tbe_id")).append("'");
		List<Object> tbebcm = new ArrayList<Object>();
		tbebcm = AccessDataBaseUtil.query4List(buff.toString(), null);
		if(tbebcm != null && tbebcm.size() > 0){
			String str = tbebcm.get(0).toString();
			if(!"104-1".equals(str) && !"104-2".equals(str) && !"104-3".equals(str)){
				if(StringUtils.isNotBlank(kind)){
					buff.setLength(0);
					String s = "";
					if("105-8".equals(kind) || "105-9".equals(kind)){
						s = "104-6";
					}else if("105-7".equals(kind) || "105-2".equals(kind)){
						s = "104-4";
					}else if("105-6".equals(kind)){
						s = "104-5";
					}
					if(!"".equals(s)){
						buff.append("update tb_employee set TBE_BIRTH_CONTROL_MEASURES = '").append(s).append("' where tbe_id = '").append(jsonObject.getString("tbe_id")).append("'");
						sqllist.add(buff.toString());
						buff.setLength(0);
					}
				}
			}
		}
		AccessDataBaseUtil.executeSQLUpdate(sqllist);
		return "\"修改成功\"";
	}

	@Override
	public Object delete(Object jsonArray) throws Exception {
		
		UserBean user = (UserBean)this.getRequest().getSession().getAttribute("userBean");
		List<String> list = new ArrayList<String>();
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		String id = jsonObject.getString("ids");
		String[] ids = id.split(",");
		id = "'"+id.replaceAll(",", "','")+"'";
		sql = "delete from tma_provide_main where tmapm_id = ?";
		StringBuffer buff = new StringBuffer();
		buff.append("select b.tmad_id,b.tmapd_num,a.reserve5 from tma_provide_main a left join tma_provide_detail b on a.tmapm_id=b.tmapm_id where b.tmapm_id in(").append(id).append(")");
		List<Object[]> result = new ArrayList<Object[]>();
		result = AccessDataBaseUtil.query(buff.toString(), null);
		for(int i = 0; i < result.size(); i++){
			String tmaom_id = AccessDataBaseUtil.getPKUUID();
			String curTime = FormatUtil.getCurentDateTime();
			buff.setLength(0);
			Object[] obj = result.get(i);
			buff.append("select a.TMAMVM_ID from tma_medicine_vistor_detail a left join tma_medicine_vistor_main b on a.TMAMVM_ID=b.TMAMVM_ID where b.reserve5='").append(obj[2]).append("'");
			List<Object> temp = new ArrayList<Object>();
			temp = AccessDataBaseUtil.query4List(buff.toString(), null);
			if(temp.size() > 0){
				return "{\"result\":false,\"resultmessage\":\"调用失败\",\"resultrecord\":\"该记录已经随访不能删除。\"}";
			}else{
				buff.setLength(0);
				buff.append("delete from tma_medicine_vistor_main where reserve5 = '").append(obj[2]).append("'");
				list.add(buff.toString());
			}
			
			buff.setLength(0);
			
			//出库主表
			buff.append("insert into tma_outcome_main(tmaom_id,org_id,tmaom_type,tmaom_is_valid,tmaom_code,tmaom_time,create_by,create_time,last_modify_by,last_modify_time) values(")
				.append("'").append(tmaom_id).append("'")
				.append(",'").append(user.getCurOrgId()).append("'")
				.append(",'").append("0").append("'")
				.append(",'").append("1").append("'")
				.append(",'").append("KM"+FormatUtil.getCurentDateTime4ms()).append("'")
				.append(",'").append(curTime).append("'")
				.append(",'").append(user.getUserId()).append("'")
				.append(",'").append(curTime).append("'")
				.append(",'").append(user.getUserId()).append("'")
				.append(",'").append(curTime).append("')");
			list.add(buff.toString());
			buff.setLength(0);
			//出库子表
			buff.append("insert into tma_outcome_detail(tmaom_id,tmaod_id,tmad_id,tmaod_num,create_by,create_time,last_modify_by,last_modify_time) values(")
				.append("'").append(tmaom_id).append("'")
				.append(",'").append(AccessDataBaseUtil.getPKUUID()).append("'")
				.append(",'").append(obj[0]).append("'")
				.append(",'").append(-Integer.parseInt(String.valueOf(obj[1]))).append("'")
				.append(",'").append(user.getUserId()).append("'")
				.append(",'").append(curTime).append("'")
				.append(",'").append(user.getUserId()).append("'")
				.append(",'").append(curTime).append("')");
			list.add(buff.toString());
		}
		AccessDataBaseUtil.executeSQLUpdate(list);
		AccessDataBaseUtil.deleteByIds(sql, ids);
		return "\"删除成功\"";
	}

	@Override
	public Object recordCount(Object jsonArray) throws Exception {
		return null;
	}

	@Override
	public Object setRequest(HttpServletRequest request) throws Exception {
		this.request = request;
		return request;
	}

	@Override
	public Object updateBatch(Object jsonArray) throws Exception {
		return null;
	}

	@Override
	public Object onCreate(Object jsonArray) {
		return null;
	}

	@Override
	public Object onDestory(Object jsonArray) {
		return null;
	}

	@Override
	public Object onInit(Object jsonArray) {
		return null;
	}
	
	/**
	 * 获取员工及其家庭信息
	 * @param jsonArray
	 * @return
	 */
	public Object selectPer(Object jsonArray){
		UserBean user = (UserBean)this.getRequest().getSession().getAttribute("userBean");
		
		if("0".equals(user.getUserId())){
			sql = " from tb_employee m left join tb_family_base n on m.tbe_id = n.tbe_id where 1 = 1";
		} else {
			sql = " from tb_employee m left join tb_family_base n on m.tbe_id = n.tbe_id where m.org_id in (" + user.getCurSubOrgIds(user.getCurOrgId()) + ") ";
		}
		
		JSONArray array = JSONArray.fromObject(jsonArray);
		if(array.size() > 0) {
			JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
			String types = jsonObject.getString("types");
			if("init".equals(types)) {// 初始查询
				
			} else if("serch1".equals(types)) {// 条件查询
				String orgIds = jsonObject.getString("orgIds_query");//机构ID串
				String forms = jsonObject.getString("tbe_employment_forms_query");//用工形式
				String tbe_name = jsonObject.getString("tbe_name_query");//姓名
				String tbe_idcard = jsonObject.getString("tbe_idcard_query");//身份证
				
				StringBuffer buff = new StringBuffer();
				if(StringUtils.isNotBlank(orgIds)){
					buff.append(" and m.org_id = '").append(orgIds).append("'");
				}
				if(StringUtils.isNotBlank(forms)){
					if(!"0".equals(forms)){//全部
						buff.append(" and m.tbe_employment_forms = '").append(forms).append("'");
					}
				}
				if(StringUtils.isNotBlank(tbe_name)){
					buff.append(" and m.tbe_name like '%").append(tbe_name).append("%'");
				}
				if(StringUtils.isNotBlank(tbe_idcard)){
					buff.append(" and m.tbe_idcard like '%").append(tbe_idcard).append("%'");
				}
				sql += buff.toString();
			} else if("serch2".equals(types)) {// 高级查询
				String where = jsonObject.getString("where");//机构ID串
				sql += where;
			}
		}
		// 排序
		String[] fields2 = {
				"tbe_id","org_id","tbe_idcard","tbe_work_permit",
				"tbe_employment_forms","tbe_name","tbe_former_name","tbe_spell_code","tbe_sex","tbe_age","tbe_birthday","tbe_nation","tbe_native_palce",
				"tbe_birthplace","tbe_join_time","tbe_seniority","tbe_family_phone","tbe_mobile","tbe_address","tbe_marital_status","tbe_marital_condition",
				"tbe_married_time","tbe_marriage_certificate","tbe_political_status","tbe_qualification","tbe_graduate_college","tbe_major","tbe_work_area",
				"tbe_position","tbe_is_again_birth","tbe_is_barrenness","the_is_menopause","tbe_is_late_marriage","tbe_is_late_birth","tbe_status","tbe_ba_status",
				"tbe_birth_control_measures","tbe_es_time","tbe_is_es","tbe_es_reason","tbe_children_status","tbe_order","tbe_memo","tbfi_children_num","tbfi_spouse_name","reserve1"
		};
		String countSql = "select count(*) " + sql;
		String sortname = this.getRequest().getParameter("sortname");
		String sortorder = this.getRequest().getParameter("sortorder");
		if(sortname != null && sortname != null) {
			sql += " order by " + sortname + " " + sortorder;
		}
		String querySql = "select m.tbe_id,m.org_id,m.tbe_idcard,m.tbe_work_permit,m.tbe_employment_forms,m.tbe_name,m.tbe_former_name,m.tbe_spell_code,m.tbe_sex,m.tbe_age,m.tbe_birthday,m.tbe_nation,m.tbe_native_palce,m.tbe_birthplace,m.tbe_join_time,m.tbe_seniority,m.tbe_family_phone,m.tbe_mobile,m.tbe_address,m.tbe_marital_status,m.tbe_marital_condition,m.tbe_married_time,m.tbe_marriage_certificate,m.tbe_political_status,m.tbe_qualification,m.tbe_graduate_college,m.tbe_major,m.tbe_work_area,m.tbe_position,m.tbe_is_again_birth,m.tbe_is_barrenness,m.the_is_menopause,m.tbe_is_late_marriage,m.tbe_is_late_birth,m.tbe_status,m.tbe_ba_status,m.tbe_birth_control_measures,m.tbe_es_time,m.tbe_is_es,m.tbe_es_reason,m.tbe_children_status,m.tbe_order,m.tbe_memo,n.tbfi_children_num,n.tbfi_spouse_name,m.reserve1 " + sql;
		return AccessDataBaseUtil.query4SQLPagging(fields2, countSql, querySql, this.getPage(), this.getPagesize(), null);
		
	}
	/** 
	 * 描述：selectTmaDictionaryById 根据Id查询药具信息及开始使用时间
	 * @param jsonArray
	 * @return
	 * @throws Exception
	 * @CreateOn Jul 10, 2012  5:12:42 PM
	 * @author liu_zhaojun
	 */
	public Object selectTmaDictionaryById(Object jsonArray) throws Exception {
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		UserBean user = (UserBean)(this.getRequest()).getSession().getAttribute("userBean");
		String org_id = user.getCurOrgId();
		String tmad_id = jsonObject.getString("tmad_id");
		String tbe_id = jsonObject.getString("tbe_id");
		StringBuffer buff = new StringBuffer("select a.tmad_description,a.tmad_spec,a.tmad_unit,a.tmad_company_name,a.tmad_batch_code,a.tmad_qgp,a.tmad_price,(sum(kc.num)-(case when kl.num_s is null then 0 else kl.num_s end)) as num");
		buff.append(",(select min(n.tmapm_begin_time) from tma_provide_detail m,tma_provide_main n where m.tmapm_id=n.tmapm_id and m.tmad_id='").append(tmad_id).append("' and n.tbe_id='").append(tbe_id).append("') as tmapm_begin_time")
		.append(" from tma_dictionary a inner join tm_general_dictionary b on a.tmad_kind=b.tmgd_id and b.tmgd_type='105' and a.tmad_id='").append(tmad_id).append("'")
		.append(" left join kucun kc on a.tmad_id=kc.id and kc.orgid='").append(org_id).append("'")
		.append(" left join (select k.tmad_id as id,sum(k.tmaod_num) as num_s from tma_outcome_detail k inner join tma_outcome_main l on k.tmaom_id=l.tmaom_id and l.tmaom_type in ('2','3','4') and l.tmaom_is_valid='1' and l.orgid='").append(org_id).append("' group by k.tmad_id) kl on kc.id = kl.id")
		.append(" where a.tmad_status = '0' group by a.tmad_description,a.tmad_spec,a.tmad_unit,a.tmad_company_name,a.tmad_batch_code,a.tmad_qgp,a.tmad_price");
		String[] fields3 = {"tmad_description","tmad_spec","tmad_unit","tmad_company_name","tmad_batch_code","tmad_qgp","tmad_price","num","tmapm_begin_time"};
		JSONArray temp = JSONArray.fromObject(AccessDataBaseUtil.query(fields3, buff.toString(), null));
		return temp.toString().substring(1, temp.toString().length()-1);
	}
	
	/** 
	 * 描述：selectTmaDictionary 查询药具名称
	 * @param jsonArray
	 * @return
	 * @throws Exception
	 * @CreateOn Jul 10, 2012  5:12:42 PM
	 * @author liu_zhaojun
	 */
	public Object selectTmaDictionary(Object jsonArray) throws Exception {
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		String tmgd_id = jsonObject.getString("tmgd_id");
		sql = "select tmad_id,tmad_name from tma_dictionary where tmad_kind=? and tmad_status='0' and reserve1 = '1' ";
		String[] fields = {"tmad_id","tmad_name"};
		JSONArray temp = JSONArray.fromObject(AccessDataBaseUtil.query(fields, sql, new Object[]{tmgd_id}));
		return temp;
	}
	/** 
	 * 描述：copyHis 复制历史
	 * @param jsonArray
	 * @return
	 * @throws Exception
	 * @CreateOn Jul 10, 2012  5:12:42 PM
	 * @author liu_zhaojun
	 */
	public Object copyHis(Object jsonArray) throws Exception {
		UserBean user = (UserBean)this.getRequest().getSession().getAttribute("userBean");
		Object[] params = null;
		StringBuffer querySql = new StringBuffer();
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.MONTH, -1);
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
		String hisdate = format.format(cal.getTime());
		cal = Calendar.getInstance();
		String nowdate = format.format(cal.getTime());
		if("0".equals(user.getUserId())){
			return "{\"Total\":\"0\",\"Rows\":[]}";
		} else {
			sql = "from tma_provide_main t left join tb_employee m on t.tbe_id = m.tbe_id left join tb_family_base n on t.tbe_id = n.tbe_id left join tma_provide_detail v on t.tmapm_id = v.tmapm_id left join tma_dictionary w on v.tmad_id = w.tmad_id where t.tmapm_time like '%"+hisdate+"%' and t.org_id = '"+user.getCurOrgId()+"' and t.tbe_id not in(select tbe_id from tma_provide_main where tmapm_time like'%"+nowdate+"%')";
		}
		JSONArray array = JSONArray.fromObject(jsonArray);
		String[] fields2 = {"tmad_kind","tmad_id1","tmapm_id","tbe_id","tbe_idcard","org_id","tmapm_code","tmapm_style","tmapm_person","tmapm_time","tmapm_begin_time","tmapm_reason","tmapm_last_medicine","tmapm_is_fail","tmapm_fail_reason","tbe_name",
				"tbe_work_permit","tbe_address","tbe_sex","tbe_age","tbe_qualification","tbfi_children_num","tbfi_spouse_name","tmapd_id","tmad_name","tmapd_num",
				"tmapm_memo","reserve1","reserve2","reserve3","reserve4","reserve5","create_by","create_time","last_modify_by","last_modify_time"
		};
		if(array.size() > 0) {
			//JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
//				String personname_query = jsonObject.getString("personname_query");//领药人姓名
//				String age_query = jsonObject.getString("age_query");//年龄
//				String tmapm_style_query = jsonObject.getString("tmapm_style_query");//发放形式
//				String tmapm_time_start = jsonObject.getString("tmapm_time_start");
//				String tmapm_time_end = jsonObject.getString("tmapm_time_end");
//				StringBuffer buff = new StringBuffer();
//				if(StringUtils.isNotBlank(tmapm_style_query)){
//					buff.append(" and t.tmapm_style = '").append(tmapm_style_query).append("'");
//				}
//				if(StringUtils.isNotBlank(age_query)){
//					buff.append(" and w.tmad_name like '%").append(age_query).append("%'");
//				}
//				if(StringUtils.isNotBlank(personname_query)){
//					buff.append(" and m.tbe_name like '%").append(personname_query).append("%'");
//				}
//				if(StringUtils.isNotBlank(tmapm_time_start)){
//					buff.append(" and t.tmapm_time >= '").append(tmapm_time_start).append("'");
//				}
//				if(StringUtils.isNotBlank(tmapm_time_end)){
//					buff.append(" and t.tmapm_time <= '").append(tmapm_time_end).append("'");
//				}
//				sql += buff.toString();
		}
		String countSql = "select count(*) " + sql;
		querySql.append("select w.tmad_kind,w.tmad_id,'',t.tbe_id,m.tbe_idcard,t.org_id,t.tmapm_code,t.tmapm_style,t.tmapm_person,'").append(FormatUtil.getCurentDate()).append("',t.tmapm_begin_time,t.tmapm_reason,t.tmapm_last_medicine,t.tmapm_is_fail,t.tmapm_fail_reason,m.tbe_name,m.")
				.append("tbe_work_permit,m.tbe_address,m.tbe_sex,m.tbe_age,m.tbe_qualification,n.tbfi_children_num,n.tbfi_spouse_name,'',w.tmad_name,v.tmapd_num,t.tmapm_memo, ")
				.append("t.reserve1,'',t.reserve3,t.reserve4,t.reserve5,t.create_by,t.create_time,t.last_modify_by,t.last_modify_time ").append(sql)
				.append(" order by last_modify_time desc");
		return AccessDataBaseUtil.query4SQLPagging(fields2, countSql, querySql.toString(), this.getPage(), this.getPagesize(), params);
	}
	/** 
	 * 描述：copySave 批量发放
	 * @param jsonArray
	 * @return
	 * @throws Exception
	 * @CreateOn Jul 10, 2012  5:12:42 PM
	 * @author liu_zhaojun
	 */
	public Object copySave(Object jsonArray) throws Exception {
		UserBean user = (UserBean)this.getRequest().getSession().getAttribute("userBean");
		JSONArray array = JSONArray.fromObject(jsonArray);
		String curTime = FormatUtil.getCurentDateTime();
		StringBuffer buff = new StringBuffer();
		String userid = user.getUserId();
		String orgid = user.getCurOrgId();
		List<String> list = new ArrayList<String>();
		String tmapmid = "";
		for(int i = 0; i < array.size(); i++){
			JSONObject jsonObject = JSONObject.fromObject(array.getString(i));
			String sn = FormatUtil.getCurentDateTime4ms();
			//药具发放主表
			int months = jsonObject.containsKey("months") ? Integer.parseInt(jsonObject.getString("months")) : 1;
			Calendar cal = Calendar.getInstance();
			Date d = FormatUtil.getDate(jsonObject.getString("tmapm_time"));
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
			cal.setTime(d);
			buff.setLength(0);
			String reserve2 = jsonObject.getString("reserve2"); 
			List<Object[]> l = new ArrayList<Object[]>();
			if(d != null){
				buff.append("select tmapm_time,tmapm_id from tma_provide_main where tmapm_time like '%").append(format.format(d))
				.append("%' and tbe_id = '").append(jsonObject.getString("tbe_id")).append("' and org_id = '").append(user.getCurOrgId()).append("' order by tmapm_time");
				l = AccessDataBaseUtil.query(buff.toString(), null);
			}
			if(l.size() > 0 && !jsonObject.getString("tmapm_id").equals(l.get(0)[1])){
				continue;
			}
			buff.setLength(0);
			tmapmid = AccessDataBaseUtil.getPKUUID();
			buff.append("insert into tma_provide_main(tmapm_id,tbe_id,org_id,tmapm_code,tmapm_style,tmapm_person,tmapm_time,tmapm_begin_time,tmapm_reason,")
			.append("tmapm_last_medicine,tmapm_is_fail,tmapm_fail_reason,tmapm_memo,reserve1,reserve2,reserve3,reserve4,reserve5,create_by,create_time,")
			.append("last_modify_by,last_modify_time) values('").append(tmapmid).append("'")
			.append(",'").append(jsonObject.getString("tbe_id")).append("'")
			.append(",'").append(orgid).append("'")
			.append(",'").append("FL"+sn+i).append("'")
			.append(",'").append(jsonObject.getString("tmapm_style")).append("'")
			.append(",'").append(jsonObject.getString("tmapm_person")).append("'")
			.append(",'").append(jsonObject.getString("tmapm_time")).append("'")
			.append(",'").append(jsonObject.getString("tmapm_begin_time")).append("'")
			.append(",'").append(jsonObject.getString("tmapm_reason")).append("'")
			.append(",'").append(jsonObject.getString("tmapm_last_medicine")).append("'")
			.append(",'").append(jsonObject.getString("tmapm_is_fail")).append("'")
			.append(",'").append(jsonObject.getString("tmapm_fail_reason")).append("'")
			.append(",'").append(jsonObject.getString("tmapm_memo")).append("'")
			.append(",'").append(jsonObject.getString("reserve1")).append("'")
			.append(",'").append(reserve2).append("'")
			.append(",'").append(jsonObject.getString("reserve3")).append("'")
			.append(",'").append(jsonObject.getString("reserve4")).append("'")
			.append(",'").append(jsonObject.getString("reserve5")).append("'")
			.append(",'").append(userid).append("'")
			.append(",'").append(curTime).append("'")
			.append(",'").append(userid).append("'")
			.append(",'").append(curTime).append("')");
			list.add(buff.toString());
			
			buff.setLength(0);
			//发放子表
			String tmapdid = AccessDataBaseUtil.getPKUUID();
			buff.append("insert into tma_provide_detail(tmapm_id,tmapd_id,tmad_id,tmapd_num,reserve1,reserve2,reserve3,reserve4,reserve5,create_by,create_time,last_modify_by,last_modify_time) values(")
				.append("'").append(tmapmid).append("'")
				.append(",'").append(tmapdid).append("'")
				.append(",'").append(jsonObject.getString("tmad_id1")).append("'")
				.append(",'").append(jsonObject.getString("tmapd_num")).append("'")
				.append(",'','','','',''")
				.append(",'").append(userid).append("'")
				.append(",'").append(curTime).append("'")
				.append(",'").append(userid).append("'")
				.append(",'").append(curTime).append("')");
			list.add(buff.toString());
			buff.setLength(0);
			if("1".equals(reserve2)){
				//出库主表
				buff.append("insert into tma_outcome_main(tmaom_id,org_id,tmaom_type,tmaom_is_valid,tmaom_code,tmaom_time,create_by,create_time,last_modify_by,last_modify_time) values(")
					.append("'").append(tmapmid).append("'")
					.append(",'").append(orgid).append("'")
					.append(",'").append("0").append("'")
					.append(",'").append("1").append("'")
					.append(",'").append("KM"+sn).append("'")
					.append(",'").append(curTime).append("'")
					.append(",'").append(userid).append("'")
					.append(",'").append(curTime).append("'")
					.append(",'").append(userid).append("'")
					.append(",'").append(curTime).append("')");
				list.add(buff.toString());
				buff.setLength(0);
				//出库子表
				buff.append("insert into tma_outcome_detail(tmaom_id,tmaod_id,tmad_id,tmaod_num,create_by,create_time,last_modify_by,last_modify_time) values(")
					.append("'").append(tmapmid).append("'")
					.append(",'").append(AccessDataBaseUtil.getPKUUID()).append("'")
					.append(",'").append(jsonObject.getString("tmad_id1")).append("'")
					.append(",'").append(Integer.parseInt(jsonObject.getString("tmapd_num"))*months).append("'")
					.append(",'").append(userid).append("'")
					.append(",'").append(curTime).append("'")
					.append(",'").append(userid).append("'")
					.append(",'").append(curTime).append("')");
				list.add(buff.toString());
				buff.setLength(0);
				//随访登记
				String tbe_id = jsonObject.getString("tbe_id");
				String tmamvm_id = AccessDataBaseUtil.getPKUUID();
				String tmad_id = jsonObject.getString("tmad_id1");
				String tmapm_begin_time = jsonObject.getString("tmapm_begin_time");
				String tmapm_fail_reason = jsonObject.getString("tmapm_fail_reason");
				SimpleDateFormat format2=new SimpleDateFormat("yyyy-MM-dd");
				sql = "select sc_value from t_system_config where sc_key='overdueReminders'";
				List<Object> sc_key = AccessDataBaseUtil.query4List(sql, null);
				int key = sc_key.size() > 0 ? Integer.valueOf(sc_key.get(0).toString()) : 0;
				int num = getMonthNum(format2.parse(tmapm_begin_time), format2.parse(curTime),key);
				buff.append("select count(*) from tma_medicine_vistor_main where tbe_id='").append(tbe_id).append("'");
				int count = AccessDataBaseUtil.queryForInt(buff.toString(), null);
				buff.setLength(0);
				List<Object[]> tempList = null;
				if(count > 0){
					buff.append("select * from (select tmamvm_id,tbe_id,tmamvm_cmedicine_des from tma_medicine_vistor_main where tbe_id='").append(tbe_id).append("' order by last_modify_time desc) a group by a.tbe_id");
					tempList = AccessDataBaseUtil.query(buff.toString(), null);
					buff.setLength(0);
				}
				if(count == 0){
					buff.append("insert into tma_medicine_vistor_main(tmamvm_id,org_id,tbe_id,tmamvm_date,tmamvm_lmedicine_des,tmamvm_lmedicine_time,tmad_id,tmamvm_change_reason,tmamvm_cmedicine_des,tmad_begin_time,tmamvm_memo,create_by,create_time,last_modify_by,last_modify_time) values(")
					.append("'").append(tmamvm_id).append("'")
					.append(",'").append(orgid).append("'")
					.append(",'").append(tbe_id).append("'")
					.append(",'").append(curTime).append("'")
					.append(",''")
					.append(",").append(num)
					.append(",''")
					.append(",''")
					.append(",'").append(tmad_id).append("'")
					.append(",'").append(tmapm_begin_time).append("'")
					.append(",''")
					.append(",'").append(userid).append("'")
					.append(",'").append(curTime).append("'")
					.append(",'").append(userid).append("'")
					.append(",'").append(curTime).append("')");
					list.add(buff.toString());
					buff.setLength(0);
				}else{
					buff.append("insert into tma_medicine_vistor_main(tmamvm_id,org_id,tbe_id,tmamvm_date,tmamvm_lmedicine_des,tmamvm_lmedicine_time,tmad_id,tmamvm_change_reason,tmamvm_cmedicine_des,tmad_begin_time,tmamvm_memo,create_by,create_time,last_modify_by,last_modify_time) values(")
					.append("'").append(tmamvm_id).append("'")
					.append(",'").append(orgid).append("'")
					.append(",'").append(tbe_id).append("'")
					.append(",'").append(curTime).append("'")
					.append(",'").append(tempList.get(0)[2]).append("'")
					.append(",").append(num)
					.append(",''")
					.append(",'").append(tmapm_fail_reason).append("'")
					.append(",'").append(tmad_id).append("'")
					.append(",'").append(tmapm_begin_time).append("'")
					.append(",''")
					.append(",'").append(userid).append("'")
					.append(",'").append(curTime).append("'")
					.append(",'").append(userid).append("'")
					.append(",'").append(curTime).append("')");
					list.add(buff.toString());
					buff.setLength(0);
				}
			}
		}
		AccessDataBaseUtil.executeSQLUpdate(list);
		return "\"保存成功\"";
	}
}


